﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using s2b.ControleDesenvolvimentoProjetos.Util.Auxiliar;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;

namespace s2b.ControleDesenvolvimentoProjetos.UserControls
{
    public partial class WUCFuncionario : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ID_FUNC"] != null)
            {

                PreencheDados();
                btnFuncionario.Text = "Atualizar Funcionario";

            }
            else
            {
                btnFuncionario.Text = "Adicionar Funcionario";

            }
        }
        private void InserirFuncionario() {
            try
            {
                Auxiliar.ExecutaComando(String.Format("INSERT INTO FUNCIONARIO(NOME_FUNC, SOBRE_NOME, EMAIL_FUNC, CARGO, LOGIN) VALUES('{0}','{1}', '{2}', '{3}', '{4}')", txtNome.Text, txtSobrenome.Text, txtEmail.Text, ddlCargo.SelectedValue, txtLogin.Text));

                CadastrarLogin();
                lblMsg.Text = "Funcionário inserido com sucesso";


            }
            catch (Exception)
            {
                lblMsg.Text = "Erro ao inserir Funcionário!";
       
            }
          
        }

        public void CadastrarLogin() {

            if (AddUser(txtLogin.Text, txtSenha.Text))
            {
                //Display success.
                lblMsg.Text = "User added. Click Sign On to continue.";
                //Hide button.
               // butAddUser.Visible = false;
            }
            else
            {
                //Display failure.
                lblMsg.Text = "User could not be added. Choose a different name.";
            }
        
        
        }
        private bool UserExists(string UserName)
        {
            //Create a data set to read the XML file.
            DataSet dsUsers = new DataSet();
            //Use error handling in case is file missing.
            try
            {
                //Build the Users.xml file path.
                string strXMLFile = Server.MapPath(".") + "\\Users.xml";
                //Read the file
                dsUsers.ReadXml(strXMLFile, XmlReadMode.InferSchema);
                //For each row in the Users table.
                foreach (DataRow rowUser in dsUsers.Tables["Users"].Rows)
                {
                    //Check for name match.
                    if (rowUser["name"].ToString() == UserName)
                    {
                        return true;
                    }
                }
            }
            catch
            {
                //In case of error return False.
                return false;
            }
            // Otherwise, return false
            return false;
        }

        private bool AddUser(string UserName, string Password)
        {
            // If the user already exists, return False and exit.
            if (UserExists(UserName))
            {
                return false;
            }
            // Otherwise, add user to XML file.
            DataSet dsUsers = new DataSet();
            // Use error handling in case is file missing.
            try
            {
                // Build the Users.xml file path.
                string strXMLFile = Server.MapPath(".") +
                "\\Users.xml";
                // Read the file.
                dsUsers.ReadXml(strXMLFile, XmlReadMode.InferSchema);
                // Add a new row.
                DataRow rowUser = dsUsers.Tables["users"].NewRow();
                // Set Username.
                rowUser["name"] = UserName;
                // Set password (encrypted).
                rowUser["password"] =
                FormsAuthentication.HashPasswordForStoringInConfigFile
                (Password, "SHA1");
                // Add row.
                dsUsers.Tables["users"].Rows.Add(rowUser);
                // Write data set.
                dsUsers.WriteXml(strXMLFile);
                return true;
            }
            catch
            {
                // In case of error return false.
                return false;
            }
        }
        public void PreencheDados()
        {

            if (!IsPostBack)
            {

               
                SqlDataReader executa = Auxiliar.RetornaRegistros(String.Format("SELECT * FROM FUNCIONARIO WHERE ID_FUNC = {0}", Request.QueryString["ID_FUNC"]), "FUNCIONARIO");

                while (executa.Read()) {

                    txtNome.Text = executa["NOME_FUNC"].ToString();
                    txtSobrenome.Text = executa["SOBRE_NOME"].ToString();
                    txtEmail.Text = executa["EMAIL_FUNC"].ToString();
                    ddlCargo.SelectedValue = executa["CARGO"].ToString();
                }
                
                

            }
        }
        private void UpdateFuncionario() {
            Auxiliar.ExecutaComando(String.Format("UPDATE FUNCIONARIO SET NOME_FUNC = '{0}', SOBRE_NOME = '{1}', EMAIL_FUNC = '{2}', CARGO = '{3}' WHERE ID_FUNC = {4}", txtNome.Text, txtSobrenome.Text, txtEmail.Text, ddlCargo.SelectedValue, Request.QueryString["ID_FUNC"]));
           Response.Redirect("WFVisualizaFuncionario.aspx", false);
        }

        protected void btnFuncionario_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ID_FUNC"] != null)
            {
                UpdateFuncionario();

            }
            else
            {

                InserirFuncionario();

            }
            txtEmail.Text = "";
            txtNome.Text = "";
            txtSobrenome.Text = "";
            ddlCargo.SelectedIndex = -1;
            txtLogin.Text = "";
            txtSenha.Text = "";
        }
    }
}